package org.mattpayne.jrac.people.daoimpl.xml;

import java.io.File;
import java.util.List;

import org.mattpayne.jrac.people.dao.PeopleDaoExeception;

import bus.Person;

import junit.framework.TestCase;

public class TestXmlDao extends TestCase {

	private static final String FILE_NAME = "testdata.xml";

	private XmlDao xmlDao;

	private Person billGates;

	protected void setUp() throws Exception {
		super.setUp();
		this.xmlDao = new XmlDao();
		xmlDao.setFileName(FILE_NAME);

		Person person = new Person();
		person.setName("Bill Gates");
		person.setEmail("bill@msn.com");
		person.setRole("CEO");

		this.billGates = person;
	}

	protected void tearDown() throws Exception {
		super.tearDown();
		File f = new File(FILE_NAME);
		f.delete();
	}

	public final void testAddPerson() throws PeopleDaoExeception {
		addBillGates();
		addSteveJobs();
		List lst = xmlDao.getPeople();
		assertEquals(2, lst.size());
		assertTrue("Bill Gates should be in the list", lst.contains(billGates));
	}



	public final void testGetPeople() throws PeopleDaoExeception {
		testAddPerson(); // turned out to be the same...
	}

	public final void testTwoSaves() throws PeopleDaoExeception {
		addBillGates();
		Person john = new Person();
		john.setName("John Lennon");
		john.setEmail("john@apple.com");
		john.setRole("Beatle");
		xmlDao.savePerson(john);
		List lst = xmlDao.getPeople();
		p("lst="+lst);
		assertEquals(2, lst.size());
	}
	
	
	public final void testSavePerson() throws PeopleDaoExeception {
		addBillGates();
		List lst = xmlDao.getPeople();
		assertEquals("Should only be one person", 1, lst.size());
		Person bill = (Person) lst.get(0);
		assertEquals(billGates, bill);
		bill.setName("Lord of MS Windows Bill Gates");
		xmlDao.savePerson(bill);
		bill = null;
		lst = xmlDao.getPeople();
		assertEquals("Should only be one person", 1, lst.size());
		bill = (Person) lst.get(0);
		p("bill="+bill);
		p("billGates="+billGates);
		assertTrue("The new bill gates should not be the same as the old...", !billGates.equals(bill));
	}


	public final void testDeletePerson() throws PeopleDaoExeception {
		//TODO
		addBillGates();
		Person person = new Person();
		person.setName("Steve Jobs");
		person.setEmail("steve0@apple.com");
		person.setRole("CEO");
		xmlDao.addPerson(person);
		List lst = xmlDao.getPeople();
		assertEquals(2, lst.size());
		
		xmlDao.deletePerson(person);
		
		lst = xmlDao.getPeople();
		assertEquals(1, lst.size());
	}
	
	
	private void addBillGates() throws PeopleDaoExeception {

		xmlDao.addPerson(billGates);
	}

	private void addSteveJobs() throws PeopleDaoExeception {

		Person person = new Person();
		person.setName("Steve Jobs");
		person.setEmail("steve0@apple.com");
		person.setRole("CEO");
		xmlDao.addPerson(person);
	}

	private void p(String msg) {
		System.out.println(msg);
	}
}
